﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Threading;
using System.Threading.Tasks;
using GxTsSharp;
using GxTsSharp.Models;

namespace StockIndex.service
{
    public class MemoryCacheService
    {
        
        private static readonly object _lock = new object();
        
        private static MemoryCacheService _instance;

        private Thread _thread { get; }

        private static MemoryCacheService GetInstance()
        {
            if (null == _instance)
            {
                lock (_lock)
                {
                    if (null == _instance)
                    {
                        _instance = new MemoryCacheService();
                    }
                }
            }
            return _instance;
        }


        public MemoryCacheService()
        {
            _thread = new Thread(Run);
        }
        
        public static void HandleStockReport(Eagle eagle,EMarketID marketId ,int count,IntPtr quote)
        {
            for (int i = 0; i < count; i++)
            {
                StockReport xQuote = (StockReport) Marshal.PtrToStructure(quote, typeof(StockReport));
                quote += Marshal.SizeOf(typeof(StockReport));

                ushort index = xQuote.No;
                StockInfo stockInfo = eagle.DicStockInfo[marketId][index];
                MemoryDataDB.AddStockReport(stockInfo.Code, xQuote);

                MemoryDataDB.StockSnapshoot.AddOrUpdate(Util.GetStockCodeKey(stockInfo.Code, marketId), m => xQuote,
                    (x, m) => xQuote);
            }
        }

        private void Run()
        {
            for (;;)
            {
                IEnumerator<KeyValuePair<string, StockReport>> enumerator = MemoryDataDB.StockSnapshoot.GetEnumerator();
                bool has = enumerator.MoveNext();
                while (has)
                {
                    MemoryDataDB.AddStockReport(enumerator.Current.Key,enumerator.Current.Value);
                    has = enumerator.MoveNext();
                }
                enumerator.Reset();
                enumerator.Dispose();
                Thread.Sleep(3000);
            }
        }
    }
}